<template>
  <div class="min-h-screen bg-gray-50 ">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Header -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between">
          <div class="flex items-center">
            <h1 class="text-2xl font-bold text-gray-900">充电桩负荷与缓冲空间匹配（CBI 实时计算）</h1>
            <span class="ml-4 text-sm text-gray-500">当前车辆: {{ currentVehicle?.id }}</span>
          </div>
          <div class="flex space-x-2">
            <el-button @click="$router.go(-1)">返回</el-button>
            <el-button
              type="primary"
              :loading="isRefreshing"
              @click="refreshData"
            >
              {{ isRefreshing ? '同步中...' : '刷新' }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- Charging Pile List -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">充电桩列表</h2>
        <div class="space-y-3">
          <div
            v-for="pile in store.chargingPiles"
            :key="pile.id"
            class="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 cursor-pointer"
            :class="{ 'border-blue-500 bg-blue-50': selectedPile?.id === pile.id }"
            @click="selectPile(pile)"
          >
            <div class="flex-1">
              <div class="XXflex items-center space-x-2">
                <span class="font-medium">{{ pile.id }}</span>
                <span class="text-gray-600">{{ pile.name }}</span>
                <span
                  class="px-2 py-1 rounded text-xs font-medium"
                  :class="pile.status === 'available' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'"
                >
                  {{ pile.status === 'available' ? '可用' : '占用' }}
                </span>
                <span class="text-sm text-gray-500">剩余 {{ pile.remainingPower }}kW</span>
              </div>
              <div class="text-sm text-gray-400 mt-1">
                预测可信度：{{ pile.predictedConfidence }}%
                <span v-if="pile.predictedConfidence < 90" class="text-orange-500">（数据量较少）</span>
              </div>
            </div>
            <div class="text-sm text-gray-500">
              CBI 预估值: {{ calculateCBI(pile.remainingPower, requiredEnergy) }}
            </div>
          </div>
        </div>
      </div>

      <!-- Load Prediction Visualization -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
          <h2 class="text-lg font-semibold text-gray-900">负荷预测可视化</h2>
          <el-button size="small" @click="showHistoryModal = true">历史对比</el-button>
        </div>

        <div class="h-64 mb-4">
          <v-chart :option="loadPredictionOption" class="w-full h-full" />
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">当前负荷</div>
            <div class="text-xl font-bold text-blue-600">{{ selectedPile?.remainingPower || 0 }}kW</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">预测精度</div>
            <div class="text-xl font-bold text-green-600">±5kW</div>
            <div class="text-xs text-gray-400">95% 置信区间</div>
          </div>
          <div class="bg-gray-50 p-4 rounded-lg">
            <div class="text-sm text-gray-500 mb-1">预测可信度</div>
            <div class="text-xl font-bold text-orange-600">{{ selectedPile?.predictedConfidence || 0 }}%</div>
          </div>
        </div>
      </div>

      <!-- Buffer Space Assessment -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">缓冲空间判定</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="space-y-4">
            <div class="bg-blue-50 p-4 rounded-lg">
              <div class="flex items-center text-blue-800 mb-2">
                <el-icon class="mr-2"><Coin /></el-icon>
                <span class="text-sm font-medium">车辆所需充电能量</span>
              </div>
              <div class="text-lg font-bold">
                {{ batteryCapacity }}kWh × (1 - {{ currentVehicle?.soc }}%) = {{ requiredEnergy }}kWh
              </div>
            </div>

            <div class="bg-green-50 p-4 rounded-lg">
              <div class="flex items-center text-green-800 mb-2">
                <el-icon class="mr-2"><Lightning /></el-icon>
                <span class="text-sm font-medium">充电桩剩余功率</span>
              </div>
              <div class="text-lg font-bold">
                {{ selectedPile?.remainingPower || 0 }}kW（60分钟预测）
              </div>
            </div>

            <div class="bg-purple-50 p-4 rounded-lg">
              <div class="flex items-center text-purple-800 mb-2">
                <el-icon class="mr-2"><Menu /></el-icon>
                <span class="text-sm font-medium">CBI 计算</span>
              </div>
              <div class="text-lg font-bold">
                CBI = {{ selectedPile?.remainingPower || 0 }} ÷ {{ requiredEnergy }} = {{ currentCBI }}
              </div>
            </div>
          </div>

          <div class="bg-gray-50 p-6 rounded-lg">
            <div class="text-center">
              <div class="mb-4">
                <el-icon :size="48" :color="cbiStatus.color">
                  <component :is="cbiStatus.icon" />
                </el-icon>
              </div>
              <div class="text-2xl font-bold mb-2" :class="cbiStatus.textColor">
                {{ cbiStatus.text }}
              </div>
              <div class="text-sm text-gray-600">
                {{ cbiStatus.description }}
              </div>
              <div v-if="waitingTime > 0" class="text-sm text-orange-600 mt-2">
                需等待时间：{{ waitingTime }} 分钟（预计 {{ estimatedAvailableTime }} 剩余功率达 {{ requiredEnergy }}kW）
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Dispatch Matching Operations -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">调度匹配操作</h2>
        <div class="flex space-x-4 mb-4">
          <el-button
            type="primary"
            size="large"
            :disabled="currentCBI < 1"
            :loading="isAllocating"
            @click="allocateChargingPile"
          >
            {{ isAllocating ? getAllocationStepText() : '确认分配此充电桩' }}
          </el-button>

          <el-button
            v-if="currentCBI < 1"
            type="warning"
            size="large"
            @click="switchToBackup"
          >
            一键切换备用桩
          </el-button>
        </div>

        <div v-if="allocationStatus" class="mt-4 p-4 bg-green-50 border border-green-200 rounded-lg">
          <div class="text-sm font-medium text-green-800">{{ allocationStatus }}</div>
        </div>
      </div>

      <!-- Backup Options -->
      <div v-if="backupPiles.length > 0" class="bg-white rounded-lg shadow-sm p-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">备用方案</h2>
        <div class="space-y-2">
          <div
            v-for="pile in backupPiles"
            :key="pile.id"
            class="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50"
          >
            <div class="flex-1">
              <span class="font-medium">{{ pile.id }}</span>
              <span class="text-gray-600 ml-2">{{ pile.name }}</span>
              <span class="text-sm text-gray-500 ml-2">剩余 {{ pile.remainingPower }}kW</span>
            </div>
            <div class="text-sm">
              <span class="text-blue-600">CBI={{ calculateCBI(pile.remainingPower, requiredEnergy) }}</span>
              <span v-if="calculateCBI(pile.remainingPower, requiredEnergy) < 1" class="text-orange-600 ml-2">
                （需等待 {{ Math.ceil((requiredEnergy - pile.remainingPower) / 2) }} 分钟）
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- History Modal -->
    <el-dialog v-model="showHistoryModal" title="历史对比" width="600px">
      <div class="h-64">
        <v-chart :option="historyComparisonOption" class="w-full h-full" />
      </div>
      <div class="mt-4 p-4 bg-gray-50 rounded-lg">
        <div class="text-sm text-gray-600">
          近 3 天同一时段预测值 vs 实际值：10:00-11:00 平均误差 3.2kW
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores'
import {
  Coin,
  Lightning,
  Menu,
  Check,
  Close
} from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components'
import VChart from 'vue-echarts'

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
])

const router = useRouter()
const store = useAppStore()

const currentVehicle = computed(() => store.currentVehicle)
const selectedPile = ref(store.chargingPiles[0])
const isRefreshing = ref(false)
const isAllocating = ref(false)
const allocationStep = ref(0)
const allocationStatus = ref('')
const showHistoryModal = ref(false)

const batteryCapacity = 77 // kWh
const requiredEnergy = computed(() => {
  if (!currentVehicle.value) return 0
  return Math.round(batteryCapacity * (1 - currentVehicle.value.soc / 100))
})

const currentCBI = computed(() => {
  if (!selectedPile.value) return 0
  return store.calculateCBI(selectedPile.value.remainingPower, requiredEnergy.value)
})

const cbiStatus = computed(() => {
  if (currentCBI.value >= 1) {
    return {
      icon: Check,
      color: '#22c55e',
      textColor: 'text-green-600',
      text: '可调度',
      description: `缓冲空间充足：可吸收 ${requiredEnergy.value}kWh 充电需求`
    }
  } else {
    return {
      icon: Close,
      color: '#ef4444',
      textColor: 'text-red-600',
      text: '不可调度',
      description: `缓冲空间不足：需 ${requiredEnergy.value}kWh，仅可提供 ${selectedPile.value?.remainingPower || 0}kWh`
    }
  }
})

const waitingTime = computed(() => {
  if (currentCBI.value >= 1) return 0
  const shortage = requiredEnergy.value - (selectedPile.value?.remainingPower || 0)
  return Math.ceil(shortage / 2) // 假设每分钟释放2kW
})

const estimatedAvailableTime = computed(() => {
  if (waitingTime.value === 0) return ''
  const now = new Date()
  const future = new Date(now.getTime() + waitingTime.value * 60000)
  return future.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
})

const backupPiles = computed(() => {
  return store.availableChargingPiles.filter(pile => pile.id !== selectedPile.value?.id)
})

const loadPredictionOption = computed(() => ({
  title: {
    text: '充电桩负荷预测',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['预测负荷', '实际负荷', '误差范围'],
    bottom: 0
  },
  xAxis: {
    type: 'category',
    data: ['10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00']
  },
  yAxis: {
    type: 'value',
    name: '功率 (kW)'
  },
  series: [
    {
      name: '预测负荷',
      type: 'line',
      data: [45, 40, 35, 30, 35, 40, 45],
      itemStyle: { color: '#3b82f6' }
    },
    {
      name: '实际负荷',
      type: 'line',
      data: [43, 38, 37, 32, 33, 42, 47],
      itemStyle: { color: '#ef4444' }
    },
    {
      name: '误差范围',
      type: 'line',
      data: [5, 5, 5, 5, 5, 5, 5],
      lineStyle: { opacity: 0 },
      areaStyle: {
        color: 'rgba(251, 146, 60, 0.2)'
      },
      stack: 'confidence'
    }
  ]
}))

const historyComparisonOption = computed(() => ({
  title: {
    text: '历史预测准确性对比',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['预测值', '实际值'],
    bottom: 0
  },
  xAxis: {
    type: 'category',
    data: ['05-04', '05-05', '05-06']
  },
  yAxis: {
    type: 'value',
    name: '功率 (kW)'
  },
  series: [
    {
      name: '预测值',
      type: 'bar',
      data: [45, 43, 45],
      itemStyle: { color: '#3b82f6' }
    },
    {
      name: '实际值',
      type: 'bar',
      data: [42, 46, 48],
      itemStyle: { color: '#ef4444' }
    }
  ]
}))

const selectPile = (pile: any) => {
  selectedPile.value = pile
}

const calculateCBI = (remainingPower: number, requiredEnergy: number) => {
  return store.calculateCBI(remainingPower, requiredEnergy)
}

const refreshData = () => {
  isRefreshing.value = true
  setTimeout(() => {
    isRefreshing.value = false
  }, 1000)
}

const getAllocationStepText = () => {
  const steps = [
    '正在校验充电桩实时状态...',
    '正在锁定资源...',
    '分配成功！'
  ]
  return steps[allocationStep.value] || '处理中...'
}

const allocateChargingPile = () => {
  isAllocating.value = true
  allocationStep.value = 0

  const steps = [
    () => {
      allocationStep.value = 1
      setTimeout(steps[1], 1500)
    },
    () => {
      allocationStep.value = 2
      setTimeout(steps[2], 1500)
    },
    () => {
      isAllocating.value = false
      allocationStatus.value = `分配成功！调度状态已更新为'待充电'`
      setTimeout(() => {
        allocationStatus.value = ''
      }, 5000)
    }
  ]

  setTimeout(steps[0], 1000)
}

const switchToBackup = () => {
  const bestBackup = backupPiles.value.reduce((best, current) => {
    const bestCBI = calculateCBI(best.remainingPower, requiredEnergy.value)
    const currentCBI = calculateCBI(current.remainingPower, requiredEnergy.value)
    return currentCBI > bestCBI ? current : best
  })

  selectedPile.value = bestBackup
  const newCBI = calculateCBI(bestBackup.remainingPower, requiredEnergy.value)
  const waitTime = newCBI < 1 ? Math.ceil((requiredEnergy.value - bestBackup.remainingPower) / 2) : 0

  allocationStatus.value = `已切换至 ${bestBackup.id}，CBI=${newCBI}${waitTime > 0 ? `（需等待 ${waitTime} 分钟）` : ''}`

  setTimeout(() => {
    allocationStatus.value = ''
  }, 5000)
}

onMounted(() => {
  if (!currentVehicle.value) {
    router.push('/monitor')
  }
})
</script>